package cn.z2huo.knowledge.concurrency.lock.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>{@link ReentrantLock} 的 {@link Condition} 测试，创建多个条件
 *
 * @author z2huo
 */
class BoundedBuffer<E> {

    private final Lock lock = new ReentrantLock();

    private final Condition notFull = lock.newCondition();

    private final Condition notEmpty = lock.newCondition();

    private final Object[] items = new Object[100];

    private int putPtr, takePtr, count;

    public void put(E x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) {
                notFull.await();
            }
            items[putPtr] = x;
            // 当数组填满时，将 putPtr 重置为 0，重新从数组开始位置填充
            if (++putPtr == items.length) {
                putPtr = 0;
            }
            ++count;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public E take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.await();
            }
            E x = (E) items[takePtr];
            // 当已经取到数组末尾时，将 takePtr 重置为 0，重新从数组开始位置获取数据
            if (++takePtr == items.length) {
                takePtr = 0;
            }
            --count;
            notFull.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }

}
